import { EnumJSBridgeWebView } from '../ConfigRegister';
import { BaseJSBridge } from './BaseJSBridge';

export class JSBridgeRegister<
    K extends keyof EnumJSBridgeWebView = keyof EnumJSBridgeWebView
> extends BaseJSBridge<EnumJSBridgeWebView> {

    constructor(private ev: K[]) {
        super()
        // 构造时一次性对所有事件调用 registerNative
        this.ev.forEach(eventName => this.registerNative(eventName))
    }

    protected setupBridge(callback: (bridge: any) => void): void {
        const _win: any = window;
        if (_win.WKWebViewJavascriptBridge) {
            callback(_win.WKWebViewJavascriptBridge);
        } else {
            _win.WKWVJBCallbacks = _win.WKWVJBCallbacks || [];
            _win.WKWVJBCallbacks.push(callback);
            _win.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null);
        }
    }

    /** 
     * 在原生或父窗口注册回调，回调里只管 `emit`
     */
    private registerNative(eventName: keyof EnumJSBridgeWebView): void {
        if (this.isAndroid) {
            (window as any).WebViewJavascriptBridge.registerHandler(
                eventName,
                (data: any, responseCallback: (res: any) => void) => {
                    this.emit(eventName, data)
                }
            )
        } else if (this.isIOS) {
            this.setupBridge((bridge: any) => {
                bridge.registerHandler(
                    eventName,
                    (data: any, responseCallback: (res: any) => void) => {
                        this.emit(eventName, data)
                    }
                )
            })
        } else {
            window.addEventListener('message', event => {
                const { type, data } = event.data || {}
                if (type === eventName) {
                    this.emit(eventName, data)
                }
            })
        }
    }
}